package 代码随想录.字符串.反转字符串Ⅱ;

/**lc：541 反转字符串Ⅱ
 * link：https://leetcode-cn.com/problems/reverse-string-ii/
 * @author ChenweiLin
 * @create 2021-12-22 10:30
 */
public class ReverseStringii {
    public static void main(String[] args) {

    }

    class Solution {
        public String reverseStr(String s, int k) {
            char[] chars = s.toCharArray();
            for(int i = 0; i < s.length();i += 2*k){
                //反转前k个
                int head = i;
                int tail = Math.min(head+k-1,s.length()-1);//这样可以处理掉第二个需求
                //即如果剩余字符少于 k 个，则将剩余字符全部反转。
                while(head < tail){
                    char temp = chars[head];
                    chars[head++] = chars[tail];
                    chars[tail--] = temp;
                }
            }

            return new String(chars);
        }
    }
}
